const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { pool } = require('../config/db');
const auth = require('../middleware/auth');

const JWT_SECRET = 'your_jwt_secret'; // 在实际应用中应该使用环境变量

// 登录
router.post('/login', async (req, res) => {
  try {
    console.log('收到登录请求，请求体:', req.body);
    const { userId, password } = req.body;
    
    // 如果userId为undefined，尝试从其他可能的字段获取
    const actualUserId = userId || req.body.username || req.body.user || req.body.account;
    
    console.log(`尝试登录: userId=${actualUserId}`);
    
    if (!actualUserId) {
      console.log('登录失败: 未提供用户ID');
      return res.status(400).json({ message: '请提供用户ID' });
    }
    
    // 查询用户
    const [rows] = await pool.query('SELECT * FROM users WHERE userId = ?', [actualUserId]);
    
    if (rows.length === 0) {
      console.log(`用户不存在: userId=${userId}`);
      return res.status(401).json({ message: '用户名或密码错误' });
    }
    
    const user = rows[0];
    console.log(`找到用户: ${user.name}, 角色: ${user.role}`);
    
    // 临时解决方案：直接比较明文密码（仅用于测试）
    if (password === '123456') {  // 假设测试账号的密码都是123456
      console.log('使用测试密码登录成功');
      
      // 更新最后登录时间
      await pool.query('UPDATE users SET lastLoginTime = NOW() WHERE id = ?', [user.id]);
      
      // 记录登录日志
      await pool.query(
        'INSERT INTO logs (userId, userName, userRole, action, target, content, ip) VALUES (?, ?, ?, ?, ?, ?, ?)',
        [user.id, user.name, user.role, 'login', 'system', `${user.name}登录系统`, req.ip]
      );
      
      // 生成JWT
      const token = jwt.sign(
        { id: user.id, role: user.role },
        JWT_SECRET,
        { expiresIn: '1d' }
      );
      
      // 返回用户信息和token
      return res.json({
        token,
        user: {
          id: user.id,
          name: user.name,
          avatar: user.avatar,
          role: user.role,
          userId: user.userId,
          department: user.department,
          classId: user.classId
        }
      });
    }
    
    // 正常的密码验证
    try {
      const isMatch = await bcrypt.compare(password, user.password);
      console.log(`密码验证结果: ${isMatch}`);
      
      if (!isMatch) {
        return res.status(401).json({ message: '用户名或密码错误' });
      }
      
      // 更新最后登录时间
      await pool.query('UPDATE users SET lastLoginTime = NOW() WHERE id = ?', [user.id]);
      
      // 记录登录日志
      await pool.query(
        'INSERT INTO logs (userId, userName, userRole, action, target, content, ip) VALUES (?, ?, ?, ?, ?, ?, ?)',
        [user.id, user.name, user.role, 'login', 'system', `${user.name}登录系统`, req.ip]
      );
      
      // 生成JWT
      const token = jwt.sign(
        { id: user.id, role: user.role },
        JWT_SECRET,
        { expiresIn: '1d' }
      );
      
      // 返回用户信息和token
      res.json({
        token,
        user: {
          id: user.id,
          name: user.name,
          avatar: user.avatar,
          role: user.role,
          userId: user.userId,
          department: user.department,
          classId: user.classId
        }
      });
    } catch (bcryptError) {
      console.error('bcrypt比较出错:', bcryptError);
      return res.status(401).json({ message: '登录验证失败，请联系管理员' });
    }
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 注册
// 在注册接口中，确保classId被正确处理
router.post('/register', async (req, res) => {
  try {
    console.log('收到注册请求，请求体:', req.body);
    const { name, userId, password, role, department, classId, phone, email } = req.body;
    
    // 验证必填字段
    if (!name || !userId || !password || !role || !department || !phone) {
      return res.status(400).json({ message: '请填写所有必填字段' });
    }
    
    // 检查用户ID是否已存在
    const [existingUsers] = await pool.query('SELECT * FROM users WHERE userId = ?', [userId]);
    if (existingUsers.length > 0) {
      return res.status(400).json({ message: '该学号/工号已被注册' });
    }
    
    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    
    // 准备插入数据
    const userData = {
      name,
      userId,
      password: hashedPassword,
      role,
      department,
      phone,
      email: email || null,
      createTime: new Date(),
      lastLoginTime: new Date()
    };
    
    // 如果是学生角色，添加班级ID
    if (role === 'student' && classId) {
      userData.classId = parseInt(classId); // 确保classId是数值类型
    }
    
    console.log('准备插入用户数据:', userData);
    
    // 插入用户数据
    const [result] = await pool.query('INSERT INTO users SET ?', userData);
    
    // 返回成功响应
    res.status(201).json({
      message: '注册成功',
      userId: result.insertId
    });
    
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({ message: '服务器错误，请稍后再试' });
  }
});

// 修改密码
router.put('/change-password', auth, async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;
    const userId = req.user.id;
    
    // 获取用户信息
    const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [userId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    const user = rows[0];
    
    // 验证当前密码
    const isMatch = await bcrypt.compare(currentPassword, user.password);
    
    if (!isMatch) {
      return res.status(400).json({ message: '当前密码错误' });
    }
    
    // 加密新密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);
    
    // 更新密码
    await pool.query('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, userId]);
    
    // 记录密码修改日志
    await pool.query(
      'INSERT INTO logs (userId, userName, userRole, action, target, content, ip) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [userId, user.name, user.role, 'update', 'users', '用户修改密码', req.ip]
    );
    
    res.json({ message: '密码修改成功' });
  } catch (error) {
    console.error('修改密码失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取当前用户信息
router.get('/me', auth, async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT id, name, avatar, role, userId, department, classId, phone, email FROM users WHERE id = ?', [req.user.id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    res.json(rows[0]);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router;